<template>
  <div>
    <brand :brand1="brand1" :brand2="brand2"></brand>
    <el-card>
      <el-steps :space="200" :active="activenum-0" finish-status="success" >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成" status=" success"></el-step>
      </el-steps>
      <!-- tab标签 -->
      <el-form
        label-position="top"
        label-width="80px"
        :model="addGoodsInfo"
        ref="addFromRef"
        :rules="addFormRule"
      >
        <el-tabs
          tab-position="left"
          style="height: 100%;"
          v-model="activenum"
          @tab-click="tabChange"
          :before-leave="befoLeave"
        >
          <el-tab-pane label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsInfo.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model.number="addGoodsInfo.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="addGoodsInfo.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量 " prop="goods_number">
              <el-input v-model.number="addGoodsInfo.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <!-- 级联悬着器 -->
              <el-cascader
                v-model="cartArr"
                :options="goodCates"
                :props="allcate"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品参数">
            <el-form-item :label="e.attr_name" v-for="e in goodsAttr_D" :key="e.attr_id">
              <el-checkbox-group v-model="e.attr_vals">
                <el-checkbox :label="m" v-for="(m, i) in e.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品属性">
            <el-form-item :label="e.attr_name" v-for="e in goodsAttr_S" :key="e.attr_id">
              <el-input v-model="e.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品图片">
            <el-upload
              :action="url"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
              :headers="handers"
              :on-success="uploadSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              <!-- /预览图片框========================================== -->
              <el-dialog title="图片预览" :visible.sync="pictureVisible" width="50%">
                <img :src="psrc">
              </el-dialog>
            </el-upload>
          </el-tab-pane>

          <el-tab-pane label="商品内容">
            <quill-editor
              v-model="addGoodsInfo.goods_introduce"
              ref="myQuillEditor"
              :options="editorOption"
              @blur="onEditorBlur($event)"
              @focus="onEditorFocus($event)"
              @ready="onEditorReady($event)"
            ></quill-editor>

            <!-- <el-input
              resize="none"
              type="textarea"
              :rows="10"
              placeholder="请输入商品内容"
              v-model="addGoodsInfo.goods_introduce"
            ></el-input>-->
            <el-button type="primary" @click="sendAddGoods" class="sbtn">完成</el-button>
          </el-tab-pane>
          <el-tab-pane label="完成"></el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// require styles 富文本编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

export default {
  data() {
    return {
      url: `http://127.0.0.1:8888/api/private/v1/upload`,
      handers: { Authorization: window.sessionStorage.getItem('token') },
      brand1: '商品管理',
      brand2: '添加商品',
      activenum: '',
      // 商品分类级联选择器数组
      cartArr: [],
      // 添加商品信息
      addGoodsInfo: {
        goods_name: '',
        goods_cat: '',
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        goods_introduce: '',
        // 上传的图片临时路径（对象）
        pics: [],
        // 商品的参数（数组），包含 动态参数 和 静态属性
        attrs: []
      },
      // 表单验证规则
      addFormRule: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }, { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入数字', trigger: 'blur' }, { type: 'number', message: '价格必须为数字值' }],
        goods_number: [{ required: true, message: '请输入数字', trigger: 'blur' }, { type: 'number', message: '数量必须为数字值' }],
        goods_weight: [{ required: true, message: '请输入数字', trigger: 'blur' }, { type: 'number', message: '重量必须为数字值' }]
      },

      // 获取的商品分类数据
      goodCates: [],
      // 存放attr_vales的数组
      attrValList: [],
      // 获取的商品参数数据
      goodsAttr_D: [],
      // 获取的商品属性数据
      goodsAttr_S: [],
      // 商品分类及联选择器
      allcate: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 上传图片列表
      fileList: [],
      // uploadfile
      NfileList: [],
      pictureVisible: false,
      // 预览图片地址
      psrc: '',
      // 编辑器配置
      editorOption: {}
    }
  },
  methods: {
    // 获取所有商品分类
    async getAllcate() {
      let { data: res } = await this.$Http.getGoodsCategory()
      if (res.meta.status != 200) return this.$message.error(res.meta.msg)
      this.goodCates = res.data
    },
    // tab切换触发
    async tabChange() {
      let catId = this.cartArr[2]
      // 发起商品参数请求
      if (this.activenum == '1') {
        let { data: res } = await this.$Http.getGoodsAttributes(catId, 'many')
        if (res.meta.status != 200) return this.$message.error(res.meta.msg)
        res.data.forEach(e => {
          e.attr_vals = e.attr_vals.trim().split(' ')
        })
        this.goodsAttr_D = res.data
      }
      // 发起商品属性请求
      if (this.activenum == '2') {
        let { data: res } = await this.$Http.getGoodsAttributes(catId, 'only')
        if (res.meta.status != 200) return this.$message.error(res.meta.msg)
        this.goodsAttr_S = res.data
      }
    },
    // 控制跳转其他页面（只有选择三级分类）
    befoLeave(toNew, old) {
      // 控制跳转
      if (toNew != '0') {
        if (this.cartArr.length != 3) {
          this.$message.error('必须选择三级分类！')
          return false
        }
      }
      // 完成之前的操作
      if (toNew === '5') {
      }
    },
    // 监听级联悬着器
    handleChange() {
      console.log(this.cartArr)
    },
    // 上传图片逻辑 点击移除
    handleRemove(file, fileList) {
      let delurl = file.response.data.tmp_path
      this.NfileList.splice(this.NfileList.indexOf(delurl), 1)
    },
    // 点击预览
    handlePreview(file) {
      this.pictureVisible = true
      console.log(file)
      this.psrc = file.url
    },
    // 成功上传的回调
    uploadSuccess(res) {
      console.log(res)

      this.NfileList.push(res.data.tmp_path)
      this.$message.success(res.meta.msg)
    },
    // 富文本编辑器
    onEditorBlur(quill) {
      console.log('editor blur!', quill)
    },
    onEditorFocus(quill) {
      console.log('editor focus!', quill)
    },
    onEditorReady(quill) {
      console.log('editor ready!', quill)
    },
    // 点击完成按钮
    sendAddGoods() {
      this.activenum = '5'
      // 处理goods_cat
      this.addGoodsInfo.goods_cat = this.cartArr.join(',')
      // 处理attrs商品属性
      this.goodsAttr_D.forEach(e => {
        let attrlist = {}
        attrlist.attr_value = e.attr_vals.join(',')
        attrlist.attr_id = e.attr_id
        this.addGoodsInfo.attrs.push(attrlist)
      })
      // 静态属性
      this.goodsAttr_S.forEach(e => {
        let attrobj = {}
        attrobj.attr_value = e.attr_vals
        attrobj.attr_id = e.attr_id
        this.addGoodsInfo.attrs.push(attrobj)
      })
      // 处理psrc 图片数组
      console.log(this.NfileList)
      this.NfileList.forEach(e => {
        let picObj = {}
        picObj.pic = e
        this.addGoodsInfo.pics.push(picObj)
      })
      console.log(this.addGoodsInfo)
      // 表单验证
      this.$refs.addFromRef.validate(async valid => {
        console.log(valid)

        if (!valid) return
        let { data: res } = await this.$Http.addGoods(this.addGoodsInfo)
        console.log(res)
        if (res.meta.status != 201) return this.$message.error(res.meta.msg)
        this.$message.success('添加商品成功!')
        this.$router.push('/goods')
      })
    }
  },
  created() {
    this.getAllcate()
  },
  components: {
    quillEditor
  }
}
</script>
<style lang='less' scoped>
.el-checkbox {
  margin: 5px 5px 5px 0;
}
.el-dialog img {
  width: 100%;
}
.sbtn {
  margin: 10px 0;
}
</style>
